package cn.tedu.spotms.server.service.impl;

import cn.tedu.spotms.server.ex.ServiceException;
import cn.tedu.spotms.server.mapper.NewsMapper;
import cn.tedu.spotms.server.pojo.dto.NewsSimpleDTO;
import cn.tedu.spotms.server.pojo.entity.News;
import cn.tedu.spotms.server.pojo.vo.NewsSimpleVO;
import cn.tedu.spotms.server.service.INewsService;
import cn.tedu.spotms.server.web.State;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NewsServiceImpl implements INewsService {
    @Autowired(required = false)
    private NewsMapper newsMapper;

    @Override
    //添加公告
    public void addNews(NewsSimpleDTO newsSimpleDTO) {
        NewsSimpleDTO newsSimpleDTO1 = newsMapper.selectById(newsSimpleDTO.getId());
        if (newsSimpleDTO1!=null) {
            throw new ServiceException(State.ERR_EXIST,"公告已存在");
        }
        News news=new News();
       BeanUtils.copyProperties(newsSimpleDTO,news);
        int row = newsMapper.addNewNews(news);
        if (row!=1) {
            throw new ServiceException(State.ERR_OPERATION_FAILURE,"添加失败,请重新操作");
        }

    }

    @Override
    //删除公告
    public void deleteNews(Long id) {
        NewsSimpleDTO newsSimpleDTO = newsMapper.selectById(id);
        if ( newsSimpleDTO==null) {
            throw new ServiceException(State.ERR_NOT_FOUND,"公告不存在");
        }
        int row = newsMapper.deleteByNewsId(id);
        if (row!=1) {
            throw new ServiceException(State.ERR_OPERATION_FAILURE,"删除失败,请重新操作");
        }

    }

    @Override
    public void updateNews(NewsSimpleDTO newsSimpleDTO) {
        NewsSimpleDTO newsSimpl = newsMapper.selectById(newsSimpleDTO.getId());
        if (newsSimpl==null) {
            throw new ServiceException(State.ERR_NOT_FOUND,"该内容不存在");
        }
        News news =new News();
        BeanUtils.copyProperties(newsSimpleDTO,news);
        int row = newsMapper.updateNewsAll(news);
        if (row!=1) {
            throw new ServiceException(State.ERR_OPERATION_FAILURE,"修改失败");
        }
    }

    @Override
    public List<NewsSimpleVO> list() {
        return newsMapper.selectList();
    }
}
